package com.dminvoicemanager.printdoc;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_List_Expand_Helper;
import com.dminvoicemanager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_Print_Main_SalesOrder extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";
	private String USER_SETTINGS = "usersettings";
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0",
			item_result_7 = "0", PRINTER_MAC_ID;
	TextView txtHeadingReports, dmreportfromdate, dmreporttodate,
			dmdisplayrepname, printDeliveryDate, invoicediscountSummary;
	TextView txtDistributorname, txtDistributoraddress, txtDistributorphone,
			txtSalesRepname, txtSalesRepPhone, printtotinvdis;
	TextView printrefno, printdate, printcus, printtotcaseqty,
			printtotpiecesqty, printmktrettot, printgrosssalestot, printtotdis,
			printnettotal, printremark, txtDistributoraddressb,
			printcusaddress, printcusaddressb, printcusphoneno;
	String currentReportName, selectFromDate, selectToDate, currentUserTemp,
			currentUserPrefix, UserLocCode, StrPrintRefNo, StrPrintDate,
			StrPrintDebName, StrPrintCaseQty, StrPrintPiecesQty,
			StrPrintDiscount, totalInvoiceDicountStr, totalGrossSalesValueStr,
			DeliveryDate, StrPrintDebAddressA, StrPrintDebAddressB,
			StrPrintDebAddressC, StrPrintDebPhone, totPiecesInCase,
			StrItemUnitPrice, repPhone = "+94",usermobileStr = "+94", userphoneStr = "+94";
	Double PrintCaseQtyVal = 0.0, PrintPiecesQtyVal = 0.0,
			PrintSalesTotal = 0.0, PrintSalesRetTotal = 0.0,
			PrintDiscountVal = 0.0;
	String StrDisPerRatio, TransType, TotalStrPrintDiscount,
			NetTotalValuePrint, TotalInvoiceDiscount, Remarks;
	String CurrentType = "0", PrintType;
	int loopPrint = 0;
	int printIndex = 0;
	//DecimalFormat formatValues = new DecimalFormat("#,###.00");
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");
	String currentRefNo, MainRefNo, currentRefDelDate;
	String printSpaceName = "                    ";
	String printSpaceQty = "     ";
	SQLiteDatabase mydb;

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	public void PrintCurrentview(View view) {
		checkPrinter();
		if (PRINTER_MAC_ID.equals("404")) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Print_Main_SalesOrder.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("PRINTER CONFIGURATION");
			// Setting Dialog Message
			alertDialog
					.setMessage("Bluetooth Printer Not Configured .Enter Printer Address");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
		} else {
			Intent myIntent = new Intent(view.getContext(),
					DM_Print_Main_SalesOrder_Active.class);
			myIntent.putExtra("TAGIDREFNO", MainRefNo);
			myIntent.putExtra("TAGIDREFDATE", currentRefDelDate);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
		}
	}

	private void checkPrinter() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUserSettings = null;
		try {
			curUserSettings = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (curUserSettings != null) {
			if (curUserSettings.getCount() > 0) {
				while (curUserSettings.moveToNext()) {
					PRINTER_MAC_ID = curUserSettings.getString(8);
					if (PRINTER_MAC_ID.trim().length() == 0) {
						PRINTER_MAC_ID = "404";
					} else {
						PRINTER_MAC_ID = curUserSettings.getString(8);
					}
				}
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_transaction_doc_salesorder);

		Bundle bundle = getIntent().getExtras();
		currentRefNo = bundle.getString("TAGIDREFNO");
		MainRefNo = currentRefNo.trim();
		Log.v(TAG, "ZZZZZZZZZZZ 2:" + currentRefNo);
		txtDistributorname = (TextView) findViewById(R.id.salesdealernameval);
		txtDistributoraddress = (TextView) findViewById(R.id.salesdealeraddressval);
		txtDistributoraddressb = (TextView) findViewById(R.id.salesdealeraddressvalb);
		txtDistributorphone = (TextView) findViewById(R.id.salesdealerphoneval);
		txtSalesRepname = (TextView) findViewById(R.id.salesrepnameval);
		printtotinvdis = (TextView) findViewById(R.id.printtotinvdis);
		txtSalesRepPhone = (TextView) findViewById(R.id.salesrepphoneval);
		invoicediscountSummary = (TextView) findViewById(R.id.invoicediscountSummary);
		printrefno = (TextView) findViewById(R.id.printrefno);
		// txtprintsordrefno = (TextView) findViewById(R.id.printsordrefno);
		printdate = (TextView) findViewById(R.id.printdate);
		printDeliveryDate  = (TextView) findViewById(R.id.printdelvdate);
		
		printcus = (TextView) findViewById(R.id.printcus);
		printremark = (TextView) findViewById(R.id.printremark);
		// Printing summay
		printtotcaseqty = (TextView) findViewById(R.id.printcaseqty);
		printtotpiecesqty = (TextView) findViewById(R.id.printpiecesqty);
		printmktrettot = (TextView) findViewById(R.id.printmktret);
		printgrosssalestot = (TextView) findViewById(R.id.printgrosssales);
		printtotdis = (TextView) findViewById(R.id.printtotdis);
		printnettotal = (TextView) findViewById(R.id.printnettotal);

		printcusaddress = (TextView) findViewById(R.id.printcusaddress);
		printcusaddressb = (TextView) findViewById(R.id.printcusaddressb);
		printcusphoneno = (TextView) findViewById(R.id.printcusphoneno);

		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Sales Order");
		displayHeader();
		displaySalesRep();
		checkItems();

	}

	private void displaySalesRep() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor surrentsalesrep = null;
		String userSettingsQuery;
		try {
			userSettingsQuery = "SELECT s.username,r.RepName,r.RepCode,r.repPhoneNo,r.RepMob From fSalRep r,usersettings s Where r.RepCode = s.username";
			// userSettingsQuery = "SELECT * From fSalRep";
			surrentsalesrep = mydb.rawQuery(userSettingsQuery, null);
			/*
			 * String query = "SELECT * FROM usersettings"; surrentsalesrep =
			 * mydb.rawQuery(query, null);
			 */
		} catch (Exception e) {
		}
		if (surrentsalesrep != null) {
			if (surrentsalesrep.getCount() > 0) {
				while (surrentsalesrep.moveToNext()) {
					String usernameStr = surrentsalesrep.getString(1);
					String userphoneStrval = surrentsalesrep.getString(3);
					String usermobileStrvsl = surrentsalesrep.getString(4);
					
					userphoneStr = userphoneStrval.trim();
					usermobileStr = usermobileStrvsl.trim();
					
					
					if (usermobileStr.length() != 0
							&& userphoneStr.length() != 0) {
						repPhone = userphoneStr + "/" + usermobileStr;
						Log.v(TAG, "PPPPPPP 1: "+ repPhone +"/");
					} else if (usermobileStr.length() != 0
							&& userphoneStr.length() == 0) {
						repPhone = usermobileStr;
						Log.v(TAG, "PPPPPPP 2: "+ repPhone +"/");
					} else if (usermobileStr.length() == 0
							&& userphoneStr.length() != 0) {
						repPhone = userphoneStr;
						Log.v(TAG, "PPPPPPP 3: "+ repPhone +"/");
					}
					txtSalesRepname
							.setText("Sales Rep : " + usernameStr.trim());
					txtSalesRepPhone.setText("Sales Phone : " + repPhone);
				}
			}
		}
		surrentsalesrep.close();
		mydb.close();
	}

	private void displayHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curDisplayDistributor = null;
		try {
			String query = "SELECT * FROM fControl";
			curDisplayDistributor = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (curDisplayDistributor != null) {
			if (curDisplayDistributor.getCount() > 0) {
				while (curDisplayDistributor.moveToNext()) {
					String DealNameStr = curDisplayDistributor.getString(1);
					String DealAddStra = curDisplayDistributor.getString(2);
					String DealAddStrb = curDisplayDistributor.getString(3);
					String DealAddStrc = curDisplayDistributor.getString(4);
					String DealMobStr = curDisplayDistributor.getString(5);

					txtDistributorname.setText(DealNameStr);
					txtDistributoraddress.setText(DealAddStra);
					txtDistributoraddressb.setText(DealAddStrb + ", "
							+ DealAddStrc + ".");
					txtDistributorphone.setText(DealMobStr);
				}
			}
		}
		curDisplayDistributor.close();
		mydb.close();
	}

	private void checkItems() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3", "item_result_4", "item_result_5",
				"item_result_6", "item_result_6a", "item_result_7" };

		int[] totrdes = new int[] { R.id.printtrans, R.id.printindex,
				R.id.printitemname, R.id.printcasesQty, R.id.printpiecesQty,
				R.id.printdiscount, R.id.printitemssum, R.id.printrawvalue };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		Cursor allrowitemsdes = null;

		try {
			String query = "SELECT FD.RefNo,FD.Itemcode,FD.Type,FD.Amt,FD.CaseQty,FD.PiceQty,FD.Type,FH.DebCode,FDE.DebName,FH.OutDis,FD.SeqNo,FH.TxnDate,FD.DisAmt,FH.TotalDis,FH.TotalAmt,FD.BDisAmt,FD.itemDisper,FD.itemdisperval,FH.outDisVal,IM.Itemcode,IM.ItemName,FH.Remarks,FH.delvDate,FDE.DebAdd1,FDE.DebAdd2,FDE.DebAdd3,FDE.DebTele,FD.itemUnitPrice,FD.caseUnitsQty FROM FOrdHed FH INNER JOIN FOrddet FD ON FD.RefNo = FH.RefNo INNER JOIN fDebtor FDE ON FDE.DebCode = FH.DebCode INNER JOIN fItems IM ON IM.Itemcode = FD.Itemcode WHERE  FD.RefNo = '"
					+ currentRefNo + "' ORDER BY FD.TxnType";

			allrowitemsdes = mydb.rawQuery(query, null);
			if (allrowitemsdes != null) {
				if (allrowitemsdes.getCount() > 0) {
					while (allrowitemsdes.moveToNext()) {
						StrPrintRefNo = allrowitemsdes.getString(0);
						StrPrintDate = allrowitemsdes.getString(11);
						StrPrintDebName = allrowitemsdes.getString(8);
						StrDisPerRatio = allrowitemsdes.getString(9);
						StrPrintCaseQty = allrowitemsdes.getString(4);
						TransType = allrowitemsdes.getString(2);
						StrPrintPiecesQty = allrowitemsdes.getString(5);
						StrPrintDiscount = allrowitemsdes.getString(12);
						TotalStrPrintDiscount = allrowitemsdes.getString(13);
						NetTotalValuePrint = allrowitemsdes.getString(14);
						TotalInvoiceDiscount = allrowitemsdes.getString(18);
						Remarks = allrowitemsdes.getString(21);
						DeliveryDate = allrowitemsdes.getString(22);

						StrPrintDebAddressA = allrowitemsdes.getString(23);
						StrPrintDebAddressB = allrowitemsdes.getString(24);
						StrPrintDebAddressC = allrowitemsdes.getString(25);
						StrPrintDebPhone = allrowitemsdes.getString(26);
						totPiecesInCase = allrowitemsdes.getString(28);
						StrItemUnitPrice = allrowitemsdes.getString(27);

						Double StrPrintCaseQtyVal = Double
								.parseDouble(StrPrintCaseQty);
						Double StrPrintPiecesQtyVal = Double
								.parseDouble(StrPrintPiecesQty);
						Double StrPrintDiscountVal = Double
								.parseDouble(StrPrintDiscount);
						PrintDiscountVal = PrintDiscountVal
								+ StrPrintDiscountVal;
						PrintCaseQtyVal = PrintCaseQtyVal + StrPrintCaseQtyVal;
						PrintPiecesQtyVal = PrintPiecesQtyVal
								+ StrPrintPiecesQtyVal;

						// TxnType
						item_result_1 = allrowitemsdes.getString(2);
						if (item_result_1.equals("SA")) {
							String rawAmountSales = allrowitemsdes.getString(3);
							Double rawAmountSalesVal = Double
									.parseDouble(rawAmountSales);
							PrintSalesTotal = PrintSalesTotal
									+ rawAmountSalesVal;
						}
						if (item_result_1.equals("UR")
								|| item_result_1.equals("MR")) {
							String rawAmountSalesRet = allrowitemsdes
									.getString(3);
							Double rawAmountSalesRetVal = Double
									.parseDouble(rawAmountSalesRet);
							PrintSalesRetTotal = PrintSalesRetTotal
									+ rawAmountSalesRetVal;
						}

						loopPrint = loopPrint + 1;

						// Log.v(TAG, "Loading Trans Type:"+item_result_1);
						if (currentRefNo.equals(item_result_1)) {
							printIndex = printIndex + 1;
							currentRefNo = allrowitemsdes.getString(2);
							// Log.v(TAG, "Printing Same Category");
							// item_result_1 = allrowitemsdes.getString(2);
							// printindex
							item_result_2 = allrowitemsdes.getString(10);
							// printitemname
							item_result_3 = allrowitemsdes.getString(20);
							// printcasesQty
							item_result_4 = allrowitemsdes.getString(4);
							// printpiecesQty
							item_result_5 = allrowitemsdes.getString(5);
							// printdiscount
							item_result_6 = allrowitemsdes.getString(12);
							// printrawvalue
							item_result_7 = allrowitemsdes.getString(3);

							// Value Discount for an item

							String itemValDis = allrowitemsdes.getString(15);
							String itemDisPerVal = allrowitemsdes.getString(17);

							Double itemValDisAmt = Double
									.parseDouble(itemValDis);
							String StritemValDisAmt = formatValues
									.format(itemValDisAmt);
							Double itemDisPerValAmt = Double
									.parseDouble(itemDisPerVal);
							String StritemDisPerValAmt = formatValues
									.format(itemDisPerValAmt);
							double itemValueDisAmt = itemValDisAmt
									- itemDisPerValAmt;
							String StritemValueDisAmt = formatValues
									.format(itemValueDisAmt);

							String itemDisPer = allrowitemsdes.getString(16);

							String DisItemRawSumD;
							if (itemDisPer.equals("0.00")) {
								DisItemRawSumD = StritemValDisAmt + ")";
							} else if (itemValDis.equals("0.00")) {
								DisItemRawSumD = StritemDisPerValAmt + "("
										+ itemDisPer + "%)";
							} else {
								DisItemRawSumD = StritemValueDisAmt + "/"
										+ StritemDisPerValAmt + "("
										+ itemDisPer + "%)";
							}
							// Calculate Total Value For Item without Discount
							double itemRawDiscount = Double
									.parseDouble(item_result_7.replaceAll(
											"[,]", ""));
							double iemRawTot = itemRawDiscount + itemValDisAmt;
							String PrintiemRawTot = formatValues
									.format(iemRawTot);

							HashMap<String, String> maptrdes = new HashMap<String, String>();
							item_result_2 = Integer.toString(printIndex);
							maptrdes.put("item_result_1", "");
							maptrdes.put("item_result_2", item_result_2);
							maptrdes.put("item_result_3", item_result_3);
							maptrdes.put("item_result_4", item_result_4);
							maptrdes.put("item_result_5", item_result_5);
							maptrdes.put("item_result_6", DisItemRawSumD);
							// Print Cases Pieces - Item Price
							totPiecesInCase = totPiecesInCase + printSpaceName;
							totPiecesInCase = totPiecesInCase.substring(0, Math.min(3,totPiecesInCase.length()));
							double StrItemUnitPriceVal = Double.parseDouble(StrItemUnitPrice.replaceAll("[,-]", ""));
							StrItemUnitPrice = formatValues.format(StrItemUnitPriceVal);
							maptrdes.put("item_result_6a", "U:"+ totPiecesInCase + printSpaceQty +StrItemUnitPrice);
							maptrdes.put("item_result_7", PrintiemRawTot);

							// fill in the grid_item layout
							fillMapstrdes.add(maptrdes);
							SimpleAdapter adaptertrdes = new SimpleAdapter(
									this, fillMapstrdes,
									R.layout.dm_transaction_doc_invoice_raw,
									fromtrdes, totrdes);
							lvtypedes.setAdapter(adaptertrdes);

							String itemCases = item_result_4 + printSpaceName;
							String PrintStritemCases = itemCases.substring(0,
									Math.min(4, itemCases.length()));
							String itemPieces = item_result_5 + printSpaceName;
							String PrintStritemPieces = itemPieces.substring(0,
									Math.min(4, itemPieces.length()));
							String itemDicountAmt = DisItemRawSumD
									+ printSpaceName;
							String PrintStritemDicountAmt = itemDicountAmt
									.substring(0, Math.min(8,
											itemDicountAmt.length()));

							String itemRawTotal = printSpaceName
									+ item_result_7;
							String PrintStritemRawTotal = itemRawTotal
									.substring(Math.max(
											itemRawTotal.length() - 30, 0));

							// **********Printing**********

						} else {

							printIndex = printIndex + 1;
							currentRefNo = allrowitemsdes.getString(2);
							/*
							 * Log.v(TAG, "loopPrint :"+loopPrint); Log.v(TAG,
							 * "Found New Category:"+currentRefNo);
							 */
							item_result_1 = allrowitemsdes.getString(2);

							if (item_result_1.equals("SA")) {
								PrintType = "Trans : SALES";
							} else if (item_result_1.equals("UR")) {
								PrintType = "Trans : USABLE RETURN";
							} else if (item_result_1.equals("MR")) {
								PrintType = "Trans : MARKET RETURN";
							} else if (item_result_1.equals("FI")) {
								PrintType = "Trans : FREE ISSUE";
							}
							// printindex
							item_result_2 = allrowitemsdes.getString(10);
							// printitemname
							item_result_3 = allrowitemsdes.getString(20);
							// printcasesQty
							item_result_4 = allrowitemsdes.getString(4);
							// printpiecesQty
							item_result_5 = allrowitemsdes.getString(5);
							// printdiscount
							item_result_6 = allrowitemsdes.getString(9);
							// printrawvalue
							item_result_7 = allrowitemsdes.getString(3);

							// Value Discount for an item

							String itemValDis = allrowitemsdes.getString(15);
							String itemDisPerVal = allrowitemsdes.getString(17);

							Double itemValDisAmt = Double
									.parseDouble(itemValDis);
							String StritemValDisAmt = formatValues
									.format(itemValDisAmt);
							Double itemDisPerValAmt = Double
									.parseDouble(itemDisPerVal);
							String StritemDisPerValAmt = formatValues
									.format(itemDisPerValAmt);
							double itemValueDisAmt = itemValDisAmt
									- itemDisPerValAmt;
							String StritemValueDisAmt = formatValues
									.format(itemValueDisAmt);

							String itemDisPer = allrowitemsdes.getString(16);

							String DisItemRawSumD;
							if (itemDisPer.equals("0.00")) {
								DisItemRawSumD = StritemValDisAmt + ")";
							} else if (itemValDis.equals("0.00")) {
								DisItemRawSumD = StritemDisPerValAmt + "("
										+ itemDisPer + "%)";
							} else {
								DisItemRawSumD = StritemValueDisAmt + "/"
										+ StritemDisPerValAmt + "("
										+ itemDisPer + "%)";
							}
							// Calculate Total Value For Item without Discount
							double itemRawDiscount = Double
									.parseDouble(item_result_7.replaceAll(
											"[,]", ""));
							double iemRawTot = itemRawDiscount + itemValDisAmt;
							String PrintiemRawTot = formatValues
									.format(iemRawTot);

							HashMap<String, String> maptrdes = new HashMap<String, String>();
							item_result_2 = Integer.toString(printIndex);
							maptrdes.put("item_result_1", PrintType);
							maptrdes.put("item_result_2", item_result_2);
							maptrdes.put("item_result_3", item_result_3);
							maptrdes.put("item_result_4", item_result_4);
							maptrdes.put("item_result_5", item_result_5);
							maptrdes.put("item_result_6", DisItemRawSumD);
							// Print Cases Pieces - Item Price
							totPiecesInCase = totPiecesInCase + printSpaceName;
							totPiecesInCase = totPiecesInCase.substring(0, Math.min(3,totPiecesInCase.length()));
							double StrItemUnitPriceVal = Double
									.parseDouble(StrItemUnitPrice.replaceAll(
											"[,-]", ""));
							StrItemUnitPrice = formatValues.format(StrItemUnitPriceVal);
							maptrdes.put("item_result_6a", "U:"+ totPiecesInCase + printSpaceQty +StrItemUnitPrice);
							maptrdes.put("item_result_7", PrintiemRawTot);

							// fill in the grid_item layout
							fillMapstrdes.add(maptrdes);
							SimpleAdapter adaptertrdes = new SimpleAdapter(
									this, fillMapstrdes,
									R.layout.dm_transaction_doc_invoice_raw,
									fromtrdes, totrdes);
							lvtypedes.setAdapter(adaptertrdes);

							// Recreating Printing Format of the data
							String printSpaceName = "                    ";
							String printSpaceQty = "     ";

							String itemCases = item_result_4 + printSpaceName;
							String PrintStritemCases = itemCases.substring(0,
									Math.min(4, itemCases.length()));
							String itemPieces = item_result_5 + printSpaceName;
							String PrintStritemPieces = itemPieces.substring(0,
									Math.min(4, itemPieces.length()));
							String itemDicountAmt = DisItemRawSumD
									+ printSpaceName;
							String PrintStritemDicountAmt = itemDicountAmt
									.substring(
											0,
											Math.min(24,
													itemDicountAmt.length()));

							String itemRawTotal = printSpaceName
									+ item_result_7;
							String PrintStritemRawTotal = itemRawTotal
									.substring(Math.max(
											itemRawTotal.length() - 30, 0));
						}

					}

				}
			} else {
				Log.v(TAG, "***************************");
			}

			printrefno.setText("Sales Order Number : " + StrPrintRefNo);
			printdate.setText ("Sales Order Date : " + StrPrintDate);
			printcus.setText(StrPrintDebName);
			printcusaddress.setText(StrPrintDebAddressA + "," +StrPrintDebAddressB);
			printcusaddressb.setText(StrPrintDebAddressC);
			printcusphoneno.setText(StrPrintDebPhone);
			printDeliveryDate.setText("Delivery Date :" + DeliveryDate);
		    printremark.setText("Remarks : " + Remarks);
			// Print Total cases and pieces Summary
		    
		    try{
		    	Integer PrintCaseQtyValInt = PrintCaseQtyVal.intValue(); 
		    	//String printCaseQuantity = Double.toString(PrintCaseQtyVal);
		    	String printCaseQuantity = Integer.toString(PrintCaseQtyValInt);
				printtotcaseqty.setText(printCaseQuantity);
				
				Integer PrintPiecesQtyValInt = PrintPiecesQtyVal.intValue(); 
				//String printPicesQuantity = Double.toString(PrintPiecesQtyVal);
				String printPicesQuantity = Integer.toString(PrintPiecesQtyValInt);
				printtotpiecesqty.setText(printPicesQuantity);
		    }
		    catch(Exception e){
		    	String printCaseQuantity = Double.toString(PrintCaseQtyVal);
				printtotcaseqty.setText(printCaseQuantity);
				String printPicesQuantity = Double.toString(PrintPiecesQtyVal);
				printtotpiecesqty.setText(printPicesQuantity);
		    }
			
			// Print Market return total value
			String PrintSalesRetTotalStr = formatValues
					.format(PrintSalesRetTotal);// Double.toString(PrintSalesRetTotal);
			printmktrettot.setText(PrintSalesRetTotalStr);

			// Print Invoice Total Amount After Discount
			Double NetTotalValuePrintVal = Double
					.parseDouble(NetTotalValuePrint.replaceAll("[,]", ""));
			String PrintNetTotalValuePrintVal = formatValues
					.format(NetTotalValuePrintVal);
			printnettotal.setText(PrintNetTotalValuePrintVal);

			// Print Line Items Discount Value Total
			String PrintDiscountValStr = formatValues.format(PrintDiscountVal); // Double.toString(PrintDiscountVal);
			printtotdis.setText(PrintDiscountValStr);

			// Total Discount Value
			Double TotalStrPrintDiscountVal = Double
					.parseDouble(TotalStrPrintDiscount.replaceAll("[,]", ""));
			Log.v(TAG, "TotalStrPrintDiscount:" + TotalStrPrintDiscount);
			// Take Cutomer Discount Ratio Value(Part of Invoice Discount)
			Double CustomerDiscountValue = TotalStrPrintDiscountVal
					- PrintDiscountVal;
			Log.v(TAG, "CustomerDiscountValue:" + CustomerDiscountValue);
			// Customer manual discount value
			Double TotalInvoiceDiscountValCus = Double
					.parseDouble(TotalInvoiceDiscount.replaceAll("[,]", ""));
			// Print Invoice Discount Value Total
			Double totalInvoiceDicount = CustomerDiscountValue;
			totalInvoiceDicountStr = formatValues.format(totalInvoiceDicount);
			printtotinvdis.setText(totalInvoiceDicountStr);

			// Print Gross Sales Total Value
			Double totalGrossSalesValue = PrintDiscountVal
					+ totalInvoiceDicount + NetTotalValuePrintVal;
			Log.v(TAG, "totalGrossSalesValue:" + CustomerDiscountValue);
			Double StrDisPerRatioVal = Double.parseDouble(StrDisPerRatio
					.replaceAll("[,]", ""));
			if (StrDisPerRatioVal <= 0.0) {
				String printMainInvDiscount = "Header Discount";
				invoicediscountSummary.setText("Header Discount");

				totalGrossSalesValueStr = formatValues
						.format(totalGrossSalesValue);
				printgrosssalestot.setText(totalGrossSalesValueStr);
			} else {
				Double DisRatioVal = TotalStrPrintDiscountVal
						- PrintDiscountVal - TotalInvoiceDiscountValCus;
				String printMainInvDiscount = "Header Discount:"
						+ formatValues.format(DisRatioVal) + "("
						+ StrDisPerRatio + "%)";
				invoicediscountSummary.setText("Header Discount  "
						+  "("+ StrDisPerRatio + "%)");
				//invoicediscountSummary.setText("Header Discount");

				totalGrossSalesValueStr = formatValues
						.format(totalGrossSalesValue);
				printgrosssalestot.setText(totalGrossSalesValueStr);
			}

			allrowitemsdes.close();
			mydb.close();
		} catch (Exception e) {
		}
		DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
